<template>
  <div>
    <input v-model="inputText" placeholder="输入问题" />
    <button @click="submit">发送</button>
    <div>{{ responseText }}</div>
    <div v-for="(msg, idx) in messages" :key="idx">
      <span v-if="msg.role === 'user'">👤</span>
      <span v-else>🤖</span>
      {{ msg.content }}
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const inputText = ref('')
const responseText = ref('')
const sessionId = ref(null)
const messages = ref([])

const submit = async () => {
  if (!inputText.value.trim()) return
  
  responseText.value = '思考中。。。。。'
  
  // 1. 追加用户输入到对话历史
  messages.value.push({
    role: 'user',
    content: inputText.value
  });

  try {
    // 2. 调用云函数，带上 messages
    const { result } = await uniCloud.callFunction({
      name: 'callBlueLM',
      data: {
        messages: messages.value, // 传递历史对话
        sessionId: sessionId.value
      }
    })

    if (result.code === 0) {
      // 3. 追加AI回复到对话历史
      messages.value.push({
        role: 'assistant',
        content: result.data
      });
      responseText.value = result.data
      sessionId.value = result.sessionId || generateUUID()
    } else {
      throw new Error(result.message || 'API调用失败')
    }
  } catch (err) {
    console.error('Request Failed:', err);
    responseText.value = '请求失败: ' + JSON.stringify(err)
  }
}

const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
}

async function startStreamChat(prompt, sessionId) {
  // 1. 先从云函数获取签名和参数
  const { result } = await uniCloud.callFunction({
    name: 'callBlueLM',
    data: { action: 'getStreamAuth', sessionId }
  });
  if (result.code !== 0) {
    // 错误处理
    return;
  }
  const { apiUrl, headers, sessionId: sid } = result.data;

  // 2. 用 fetch + ReadableStream 进行流式请求
  const res = await fetch(apiUrl, {
    method: 'POST',
    headers: {
      ...headers,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      // prompt, // 不再单独传 prompt
      sessionId: sid,
      model: 'vivo-BlueLM-TB-Pro',
      messages: messages.value // 传递历史对话
    })
  });

  if (!res.body) return;
  const reader = res.body.getReader();
  let decoder = new TextDecoder('utf-8');
  let buffer = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    // 处理SSE分片
    let lines = buffer.split('\n');
    buffer = lines.pop(); // 可能有半截
    for (let line of lines) {
      line = line.trim();
      if (line.startsWith('data:')) {
        const dataStr = line.slice(5).trim();
        if (dataStr === '[DONE]') {
          // 结束
          return;
        }
        try {
          const dataObj = JSON.parse(dataStr);
          // 这里 dataObj.message 就是大模型的增量内容
          // 你可以把它 append 到聊天窗口
        } catch (e) {}
      }
      if (line.startsWith('event:')) {
        // 处理 event:close、event:error 等
      }
    }
  }
}
</script>